package com.niiwoo.civet.mobile.lanmao.handler;

import com.alibaba.fastjson.JSONObject;
import com.niiwoo.tripod.lanmao.enums.LanMaoGatewayServiceNameEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import java.util.Collections;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TradePasswordNotifyHandler implements LanMaoNotifyHandler {

    public static final Logger logger = LoggerFactory.getLogger(TradePasswordNotifyHandler.class);

    @Override
    public boolean supports(String serviceName) {
        return LanMaoGatewayServiceNameEnum.RESET_PASSWORD.name().equals(serviceName);
    }

    @Override
    public HandleResult handle(JSONObject json) {
        logger.error("修改密码###回调处理报文###data={}", json.toJSONString());
        TradePasswordGatewayResponse response = json.toJavaObject(TradePasswordGatewayResponse.class);
        if (response.isCallSuccess() && response.isBusinessSuccess()) {
            HandleResult result = new HandleResult();
            result.setNeedAck(true);
            result.setData(Collections.singletonMap("orderStatus", "SUCCESS"));
            result.setRequestNo(response.getRequestNo());
            return result;
        }
        throw new BizException(response.getErrorCode(), response.getErrorMessage());
    }

    @Setter
    @Getter
    private static class TradePasswordGatewayResponse {

        private static final String CALL_SUCCESS_CODE = "0";

        private static final String BUSINESS_SUCCESS_CODE = "SUCCESS";

        // 调用状态(0 为调用成功、1 为失败,返回 1 时请看【调用失败错误码】及错误码)
        private String code;

        // 业务处理状态(处理失败 INIT;处理成功 SUCCESS),平台可根据非 SUCCESS 状态做相应处理,处理失败时可参考错误码
        private String status;
        // 错误码
        private String errorCode;
        // 错误码
        private String errorMessage;

        // 请求流水号
        private String requestNo;

        // 集团账户编号
        private String groupAccountNo;

        private boolean isCallSuccess() {
            return StringUtils.isNotBlank(code) && CALL_SUCCESS_CODE.equals(code);
        }

        public boolean isBusinessSuccess() {
            return StringUtils.isNotBlank(status) && BUSINESS_SUCCESS_CODE.equals(status);
        }

    }

}
